package com.bdqn.jpayhymeleaf.contorller;

import com.bdqn.jpayhymeleaf.entity.Role;
import com.bdqn.jpayhymeleaf.entity.User;
import com.bdqn.jpayhymeleaf.service.IRoleService;
import com.bdqn.jpayhymeleaf.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;

    @RequestMapping(value = "/user/list")
    public String list(Model model, String usrName,
                       @RequestParam(required = false,defaultValue = "0")Integer roleId,
                       @RequestParam(required = false,defaultValue = "1")int pageIndex){
        Sort sort=Sort.by(Sort.Direction.ASC,"usrId");
        Pageable pageable= PageRequest.of(pageIndex-1,5,sort);
        Page<User>userPager=userService.findUsers(usrName,roleId,pageable);
        model.addAttribute("userPager",userPager);
        model.addAttribute("usrName",usrName);
        model.addAttribute("roleId",roleId);
        List<Role>roles=roleService.findALLRoles();
        model.addAttribute("roles",roles);
        return "user/list";

    }

    @RequestMapping(value = "/user/add")
    public String add(Model model){
        List<Role>roles=roleService.findALLRoles();
        model.addAttribute("role",roles);
        return "user/add";
    }
    public String save(User user){
        userService.saveUser(user);
        return "redirect:/user/list";
    }

    @RequestMapping(value = "/user/edit")
    public String edit(Long userId,Model model){
        User user=userService.getUser(userId);
        List<Role>roles=roleService.findALLRoles();
        model.addAttribute("user",user);
        model.addAttribute("roles",roles);
        return "user/edit";
    }

    @RequestMapping(value = "/user/del")
    @ResponseBody
    public Map del(Long usrId){
        userService.deleteUser(usrId);
        Map map=new HashMap();
        map.put("delResult","true");
        return map;
    }

    @RequestMapping(value = "/role/json")
    @ResponseBody
    public List<Role>findAllRoles(){
        List<Role>list=roleService.findALLRoles();
        return list;
    }
}

